package role

import (
	"context"
	"fmt"
	"github.com/gogf/gf/v2/os/gmlock"
	"github.com/gogf/gf/v2/util/gconv"
	"strconv"
	"unicode/utf8"
	"xr-game-server/core/constants/common"
	"xr-game-server/core/httpserver"
	"xr-game-server/dao/roledao"
	"xr-game-server/dao/serverdao"
	"xr-game-server/dto/roledto"
	"xr-game-server/entity"
	"xr-game-server/errercode"
	"xr-game-server/module/name"
	"xr-game-server/module/server"
)

func CreateRoleName(ctx context.Context, req *roledto.CreateRoleReq) (res *string, err error) {
	serverDB := serverdao.GetServer(req.ServerId)
	if serverDB == nil {
		return nil, errercode.CreateCode(errercode.ServerNotExist)
	}
	if !server.CanEnter(serverDB) {
		return nil, errercode.CreateCode(errercode.ServerNotOpen)
	}
	if len(req.RoleName) == common.Zero {
		return nil, errercode.CreateCode(errercode.RoleNameEmpty)
	}
	if utf8.RuneCountInString(req.RoleName) > StrLen {
		return nil, errercode.CreateCode(errercode.RoleNameOut)
	}
	//重复名称检查
	flag := name.ChkName(req.RoleName, entity.RoleNameType)
	if !flag {
		return nil, errercode.CreateCode(errercode.NameRepeat)
	}
	accountId := httpserver.GetAuthId(ctx)
	lockKey := fmt.Sprintf("role:CreateRoleName:%v", accountId)
	defer gmlock.Unlock(lockKey)
	lockFlag := gmlock.TryLock(lockKey)
	if !lockFlag {
		return nil, errercode.CreateCode(errercode.SysBuyLimit)
	}
	//开始检查角色是否重复创建
	flag = chkRoleRepeat(gconv.Uint64(accountId), req)
	if !flag {
		return nil, errercode.CreateCode(errercode.RoleRepeat)
	}
	roleData := entity.NewRole(gconv.Uint64(accountId))
	roleData.SetNick(req.RoleName)
	roleData.SetServerId(req.ServerId)
	roleData.SetAvatarId(req.AvatarId)
	roledao.AddRole(roleData)
	str := strconv.FormatUint(roleData.ID, 10)
	return &str, err
}

func chkRoleRepeat(accountId uint64, req *roledto.CreateRoleReq) bool {
	caches := roledao.GetRoleBy(accountId)
	for _, role := range caches {
		if role.ServerId == req.ServerId {
			return false
		}
	}
	return true
}
